package com.heny.demo.util;

import com.heny.demo.entity.PointData;
import com.heny.demo.entity.TurnPoint;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static org.apache.poi.ss.usermodel.Cell.*;

/**
 * @author yaonn
 * @date 2025/9/1123:03
 * @Description
 */
@Component
public class ExcelImportStrategy implements FileImportStrategy{
    @Override
    public List<PointData> importData(InputStream inputStream) throws Exception {
        List<PointData> result = new ArrayList<>();

        try (Workbook workbook = WorkbookFactory.create(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();

            if (!rowIterator.hasNext()) return result;

            // 跳过标题行
            rowIterator.next();

            // 读取数据行
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                String name = getCellValueAsString(row.getCell(0));
                double x = getCellNumericValue(row.getCell(1));
                double y = getCellNumericValue(row.getCell(2));
                double z = getCellNumericValue(row.getCell(3));

                result.add(new PointData(name, x, y, z));
            }
        }

        return result;
    }
    private String getCellValueAsString(Cell cell) {
        switch (cell.getCellType()) {
            case CELL_TYPE_STRING:
                return cell.getStringCellValue();
            case CELL_TYPE_NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case CELL_TYPE_BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case CELL_TYPE_FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
    private double getCellNumericValue(Cell cell) {
        if (cell == null) return 0;

        switch (cell.getCellType()) {
            case CELL_TYPE_NUMERIC:
                return cell.getNumericCellValue();
            case CELL_TYPE_STRING:
                try {
                    return Double.parseDouble(cell.getStringCellValue());
                } catch (NumberFormatException e) {
                    return 0;
                }
            default:
                return 0;
        }
    }
    @Override
    public boolean supports(String fileType) {
        return "xlsx".equalsIgnoreCase(fileType) || "xls".equalsIgnoreCase(fileType);
    }
}
